﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Mocola.BLL;
using Mocola.Model;
using Mocola.Web;
using Mocola.Security;
using System.Web.Security;
using System.Data.Common;

namespace Mocola.Net.Web
{
    public partial class newuser : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
            }
        }

        private void BindData()
        {
            string sql = "SELECT * FROM Moc_Departments";
            DataSet dtDepart = Databases.MocolaNet.ExecuteDataSet(CommandType.Text, sql);
            cblDepartment.DataSource = dtDepart;
            cblDepartment.DataBind();

            sql = "SELECT * FROM Moc_Roles";
            DataSet dtRoles = Databases.MocolaNet.ExecuteDataSet(CommandType.Text, sql);
            ddlRoles.DataSource = dtRoles;
            ddlRoles.DataBind();

            if (!string.IsNullOrEmpty(Request.QueryString["UserID"]))
            {
                string UserID = Request.QueryString["UserID"].ToString();

                sql = "SELECT UserID, UserName, UserPwd, UserSex, Status, LoginTimes, LastLoginTime, " +
                             "LastPwdChangeTime, LastLockTime, Email, LastName, FirstName, FullName, RoleID, Phone FROM Moc_Users " +
                             "WHERE UserID=" + UserID;

                DataSet dtUsers = Databases.MocolaNet.ExecuteDataSet(CommandType.Text, sql);

                if (dtUsers.Tables[0].Rows.Count == 1)
                {
                    txtXingMing.Text = dtUsers.Tables[0].Rows[0]["FullName"].ToString();
                    txtDengLuMing.Text = dtUsers.Tables[0].Rows[0]["UserName"].ToString();
                    ddlSex.SelectedValue = dtUsers.Tables[0].Rows[0]["UserSex"].ToString();
                    txtDianHua.Text = dtUsers.Tables[0].Rows[0]["Phone"].ToString();
                    txtEmail.Text = dtUsers.Tables[0].Rows[0]["Email"].ToString();
                    ddlRoles.SelectedValue = dtUsers.Tables[0].Rows[0]["RoleID"].ToString();
                    ddlStatus.SelectedValue = dtUsers.Tables[0].Rows[0]["Status"].ToString();
                }

                sql = "select DepartID from Moc_DepartmentUser where UserID=" + UserID;
                DataSet dtDept = Databases.MocolaNet.ExecuteDataSet(CommandType.Text, sql);
                if (dtDept.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < dtDept.Tables[0].Rows.Count; i++)
                    {
                        cblDepartment.Items[Int32.Parse(dtDept.Tables[0].Rows[i][0].ToString()) - 1].Selected = true; 
                    }
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (txtDengLuMing.Text.Trim() == string.Empty)
            {
                Alert.Show("Must input LoginID");
                txtDengLuMing.Focus();
                return;
            }

            if (string.IsNullOrEmpty(Request.QueryString["UserID"]))
            {
                if (txtMiMa.Text.Trim() == string.Empty)
                {
                    Alert.Show("Must input password");
                    txtMiMa.Focus();
                    return;
                }
                else if (txtMiMa.Text.Trim() != txtQueRenMima.Text.Trim())
                {
                    Alert.Show("Password not same!");
                    txtMiMa.Focus();
                    return;
                }
            }

            MD5Verifier md5 = new MD5Verifier();
            string UserPwd = md5.getMd5Hash(txtMiMa.Text.Trim());

            MembershipCreateStatus status = new MembershipCreateStatus();
            DbTransaction transaction = Databases.MocolaNet.BeginTransaction(IsolationLevel.ReadCommitted);

            if (string.IsNullOrEmpty(Request.QueryString["UserID"]))
            {
                try
                {
                    int nID = Databases.MocolaNet.Insert(Moc_UsersInfo.Moc_Users)
                                .AddColumn(Moc_UsersInfo.Moc_Users.UserName, txtDengLuMing.Text.Trim())
                                .AddColumn(Moc_UsersInfo.Moc_Users.FullName, txtXingMing.Text.Trim())
                                .AddColumn(Moc_UsersInfo.Moc_Users.UserPwd, UserPwd)
                                .AddColumn(Moc_UsersInfo.Moc_Users.UserSex, (ddlSex.SelectedValue == "0" ? false : true))
                                .AddColumn(Moc_UsersInfo.Moc_Users.Email, txtEmail.Text.Trim())
                                .AddColumn(Moc_UsersInfo.Moc_Users.Phone, txtDianHua.Text.Trim())
                                .AddColumn(Moc_UsersInfo.Moc_Users.RoleID, Convert.ToInt32(ddlRoles.SelectedValue))
                                .AddColumn(Moc_UsersInfo.Moc_Users.Status, (ddlStatus.SelectedValue == "0" ? false : true))
                                .SetTransaction(transaction)
                                .ExecuteReturnAutoIncrementID(Moc_UsersInfo.Moc_Users.UserID);

                    bool blTrees = false;

                    if (nID != -1)
                    {
                        blTrees = true;

                        // 插入部门关系
                        for (int i = 0; i < cblDepartment.Items.Count; i++)
                        {
                            if (cblDepartment.Items[i].Selected)
                            {
                                string sql = "INSERT INTO Moc_DepartmentUser(DepartID,UserID) VALUES({0},{1})";
                                sql = string.Format(sql, cblDepartment.Items[i].Value, nID.ToString());
                                Databases.MocolaNet.ExecuteNonQuery(CommandType.Text, sql);
                            }
                        }
                    }


                    if (blTrees)
                    {
                        Alert.Show("保存成功!");
                        status = MembershipCreateStatus.Success;
                    }
                    else
                    {
                        Alert.Show("保存失败!");
                        status = MembershipCreateStatus.ProviderError;
                    }
                }
                catch (Exception ex)
                {
                    Alert.Show(ex.Message);
                    status = MembershipCreateStatus.ProviderError;
                }
                finally
                {
                    if (status == MembershipCreateStatus.Success)
                        transaction.Commit();
                    else
                        transaction.Rollback();
                    Databases.MocolaNet.CloseConnection(transaction);
                }
            }
            else
            {
                try
                {
                    int UserID = Convert.ToInt32(Request.QueryString["UserID"]);
                    bool bUpdated = Databases.MocolaNet.Update(Moc_UsersInfo.Moc_Users)
                                    .AddColumn(Moc_UsersInfo.Moc_Users.UserName, txtDengLuMing.Text.Trim())
                                    .AddColumn(Moc_UsersInfo.Moc_Users.FullName, txtXingMing.Text.Trim())
                                    .AddColumn(Moc_UsersInfo.Moc_Users.UserPwd, UserPwd)
                                    .AddColumn(Moc_UsersInfo.Moc_Users.UserSex, (ddlSex.SelectedValue == "0" ? false : true))
                                    .AddColumn(Moc_UsersInfo.Moc_Users.Email, txtEmail.Text.Trim())
                                    .AddColumn(Moc_UsersInfo.Moc_Users.Phone, txtDianHua.Text.Trim())
                                    .AddColumn(Moc_UsersInfo.Moc_Users.RoleID, Convert.ToInt32(ddlRoles.SelectedValue))
                                    .AddColumn(Moc_UsersInfo.Moc_Users.Status, (ddlStatus.SelectedValue == "0" ? false : true))
                                    .Where(Moc_UsersInfo.Moc_Users.UserID == UserID)
                                    .SetTransaction(transaction)
                                    .Execute() == 1;
                    
                    // 删除当前用户的所有部门关系
                    string sql = "DELETE FROM Moc_DepartmentUser WHERE UserID = " + UserID;
                    Databases.MocolaNet.ExecuteNonQuery(CommandType.Text, sql);

                    // 插入编辑后的部门关系
                    for (int i = 0; i < cblDepartment.Items.Count; i++)
                    {
                        if (cblDepartment.Items[i].Selected)
                        {
                            sql = "INSERT INTO Moc_DepartmentUser(DepartID,UserID) VALUES({0},{1})";
                            sql = string.Format(sql, cblDepartment.Items[i].Value, UserID.ToString());
                            Databases.MocolaNet.ExecuteNonQuery(CommandType.Text, sql);
                        }
                    }

                    if (bUpdated)
                    {
                        Alert.Show("更新成功!");
                        status = MembershipCreateStatus.Success;
                    }
                    else
                    {
                        Alert.Show("更新失败!");
                        status = MembershipCreateStatus.ProviderError;
                    }
                }
                catch (Exception ex)
                {
                    Alert.Show(ex.Message);
                    status = MembershipCreateStatus.ProviderError;
                }
                finally
                {
                    if (status == MembershipCreateStatus.Success)
                        transaction.Commit();
                    else
                        transaction.Rollback();
                    Databases.MocolaNet.CloseConnection(transaction);
                }
            }
        }
    }
}
